library(foreign)
library(car)

save <- TRUE

setwd("~/Google Drive/Broockman/Completed/Extremity vs Consistency/ReplicationData/StateLegislatorSurvey")

data <- read.dta("state-legislator-survey.dta", convert.underscore = TRUE)
names(data)

#ANALYSIS OF 7-PART QUESTIONS
multis<-data[,c(21:30,32,31)]
multi.names <- c("Gun Control", "Health Care", "Immigration", "Taxes", "Abortion", "Environment", "Medicare", "Gay Rights", "Affirmative Action", "Unions", "Contraception", "Education")
cbind(names(multis), multi.names) #make sure names are right

multi.counts <- matrix(nrow = 7, ncol = ncol(multis)) #Rows are answers, columns are questions
for(i in 1:nrow(multi.counts)){#Loop over answers, sum the number of responses for each question that have it
	for(j in 1:ncol(multis)){#for each question...
		multi.counts[i,j] <- sum(multis[,j]==i, na.rm=TRUE)
	}
}
for(i in 1:ncol(multi.counts)){#Get opinion distribution -- Loop over questions, divide by the total number of responses
	multi.counts[,i] <- multi.counts[,i] / sum(multi.counts[,i])
}

average.opinion.across.issues <- rowSums(multi.counts, na.rm = TRUE)
	average.opinion.across.issues <- average.opinion.across.issues / sum(average.opinion.across.issues)
issue.specific.averages.across.rs <- rowMeans(multis, na.rm = TRUE)


makeplot <- function(seven.point, title, ylimtop = .45, sub=""){
	bp <- barplot(seven.point, main = title, ylim=c(0,ylimtop), names.arg = c(1:7), col = c("darkblue", "blue3", "blue", "Purple", "red", "red3", "darkred"), sub=sub)
	text(bp, seven.point + .01, paste0(round(seven.point*100, 0),"%"),cex=.9,pos=3)
}


if(save) pdf("stateleg_issues_then_respondents.pdf", width = 700*2/50, height = 500*2/50, pointsize = 16*2)
makeplot(average.opinion.across.issues,  "Distribution of Responses on 'Average Issue' - Legislators", ylimtop = .4)
if(save) dev.off()

if(save) pdf("stateleg_respondents_then_issues.pdf", width = 700*2/50, height = 500*2/50, pointsize = 16*2)
opar <- par(lwd=3)
hist(issue.specific.averages.across.rs, weights = data$weights, main = "Distribution of Respondents' Average Responses - Legislators", ylab = "Frequency", xlab = "", xlim = c(.6,7.4), breaks=30, cex=.3)
par(opar)
if(save) dev.off()